package com.example.demo.controller;

import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 测试获取用户
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("/getUser")
    public User getUser(Long id) {
        return userService.getUser(id);
    }

    /**
     * 测试添加方法
     *
     * @param userName 用户名
     * @param note     note
     * @return map集合
     */
    @RequestMapping("/insert")
    public User insertUser(String userName, String note) {
        User user = new User();
        user.setUserName(userName);
        user.setNote(note);
        userService.insertUser(user);
        return user;
    }

    @GetMapping("/findUser")
    public List<User> findUser(String userName, String note) {
        return userService.findUser(userName, note);
    }

    @PostMapping("/updateUser")
    public Map<String, Object> updateUser(Long id, String userName) {
        User user = userService.updateUser(id, userName);
        boolean flag = user != null;
        String message = flag ? "更新成功" : "更新失败";
        return resultMap(flag, message);
    }

    @DeleteMapping("deleteUserById")
    public Map<String, Object> deleteUserById(Long id){
        int i = userService.deleteUser(id);
        boolean flag = i == 1;
        String message = flag ? "删除成功" : "删除失败";
        return resultMap(flag, message);
    }

    public Map<String, Object> resultMap(boolean flag, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("flag", flag);
        map.put("message", message);
        return map;
    }
}
